<?php

/* Houses all ajax calls */

add_action('wp_ajax_get_random_word', 'get_random_word');

function get_random_word() {
  
	global $current_user;
  get_currentuserinfo();
  
  $out = array();
  query_posts('post_type=word&numberposts=1&orderby=rand');
  while ( have_posts() ) : the_post();
    
	  $images_src = array();
    
    $attachments = get_posts( array(
      
			'post_type' => 'attachment',
			'numberposts' => -1,
			'post_status' => null,
			'post_parent' => get_the_ID()
			
		) );
		
		if ( $attachments ) {
		  
			foreach ( $attachments as $attachment ) {
			  
				$images_src[] = $attachment->guid;
			  
			}
		
		}
	  
	  $titles = explode( ',', get_the_title() );
	  
		$score = $score = get_user_meta( $current_user->ID, 'score', true );
		$score = ( ! ctype_digit ( $score ) ? 0 : $score );
		
	  $out = array(
	    
	    'ID' => get_the_ID(),
	    'words' => $titles,
	    'images_src' => $images_src,
	    'score' => $score
	    
	  );
	  
  endwhile;
  
  wp_reset_query();
  
  header( 'Cache-Control: no-cache, must-revalidate' );
	header( 'Expires: Mon, 26 Jul 1997 05:00:00 GMT' );
	header( 'Content-type: application/json' );
  die( json_encode( $out ) );
  
}

add_action('wp_ajax_award_points', 'award_points');

function award_points() {
  
  if( isset ( $_POST['microtime'] ) &&
      ( $_POST['mode'] === 'learn' ||
				$_POST['mode'] === 'study' ||
					$_POST['mode'] === 'test' ) ) {
  	
		global $current_user;
  	get_currentuserinfo();
		
		$score = get_user_meta( $current_user->ID, 'score', true );
		$score = ( ! ctype_digit ( $score ) ? 0 : $score );
		$score++;
		
		if( update_user_meta( $current_user->ID, 'score', $score ) ) {
			
			die( ( microtime( true ) - $_POST['microtime'] ) * 1000 );
			
		} else {
			
			die ( '0' );
			
		}
		
	} else {
	  
	  die( '0' );
		
	}
  
}

?>